package df.applet.form;
//package pyt.df.frame;

import df.bean.db.table.Batch;
import df.bean.obj.util.DialogBox;
import df.bean.obj.util.JDate;
import df.bean.obj.util.Variables;
import df.bean.process.ProcessTransMonthly;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Rectangle;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;

//my import
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import java.net.HttpURLConnection;
import java.net.URL;

//import pyt.df.db.table.Batch;
//import pyt.df.obj.util.DialogBox;
//import pyt.df.obj.util.JDate;
//import pyt.df.obj.util.DialogBox;
//import pyt.df.obj.util.JDate;

public class SummaryMonthlyFrm extends CalculatorFrm {
    protected JPanel jPanelLayout = new JPanel();
    protected JList lstDoctorGroupCode = new JList();
    protected JTable tblMessage = null; //new JTable();
    protected JLabel statusBar = new JLabel();
    
    protected JScrollPane scrollPane;// = new JScrollPane();
    protected JScrollPane scrollPaneMessage;// = new JScrollPane();
    
    protected JList lstHospitalCode = new JList();
    protected JScrollPane scrollPaneHospitalCode;
    protected JLabel lblHospital = new JLabel();
    protected JLabel lblDoctor = new JLabel();

    protected ImageIcon imageStart = new ImageIcon(SummaryMonthlyFrm.class.getResource("start.gif"));
    protected ImageIcon imageStop = new ImageIcon(SummaryMonthlyFrm.class.getResource("stop.gif"));
    protected ImageIcon imageClose = new ImageIcon(SummaryMonthlyFrm.class.getResource("close.gif"));
    
    protected JButton start = new JButton();
    protected JButton stop = new JButton(); 
    protected JButton close = new JButton();  
    protected JSeparator jSeparator4 = new JSeparator();
    protected JPanel jPanel1 = new JPanel();
    protected JPanel jPanel2 = new JPanel();
    protected JPanel jPanel3 = new JPanel();
    protected JTextArea jTextArea1 = new JTextArea();
    protected JSeparator jSeparator1 = new JSeparator();
    protected JSeparator jSeparator5 = new JSeparator();    
    
    protected JComboBox jcboYear = new JComboBox();
    protected JComboBox jcboMonth = new JComboBox();
    protected JLabel jLabel2 = new JLabel();

    protected JLabel jLabel1 = new JLabel();


    public SummaryMonthlyFrm() {
        try {
            jbInit();
        } catch (Exception e) {
            DialogBox.ShowError("Error in CalculatorTransMonthFrm\n"+e.getMessage());
            e.printStackTrace();
        }
    }

    public void jbInit() throws Exception {
        this.setSize(new Dimension(819, 622));
        jPanelLayout.setLayout(null);
        jPanelLayout.setBackground(new Color(214, 214, 255));
        getLstDoctorGroupCode().setBounds(new Rectangle(5, 80, 200, 330));

        start.setIcon(imageStart);
        start.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        start_actionPerformed(e);
                    }
                });
        stop.setIcon(imageStop);
        stop.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        stop_actionPerformed(e);
                    }
                });
        close.setIcon(imageClose);
        close.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        close_actionPerformed(e);
                    }
                });
        
        getLstDoctorGroupCode().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);        
        scrollPane = new JScrollPane(getLstDoctorGroupCode());
        scrollPane.setBounds(new Rectangle(20, 265, 120, 305));
        jPanelLayout.add(getLblDoctor(), null);
        jPanelLayout.add(getLblHospital(), null);
        
//         scroll pane for hospital
        scrollPaneHospitalCode = new JScrollPane(getLstHospitalCode());
        scrollPaneHospitalCode.setBounds(new Rectangle(20, 205, 120, 50));
       
        //Table Scroll Pane
        String[] columnNames={ "Time", "Doctor Code","Name Thai", "Remark" }; 
        tableModel = new DefaultTableModel(columnNames, row);
        tblMessage = new JTable(tableModel);
        scrollPaneMessage = new JScrollPane(tblMessage); 
        scrollPaneMessage.setBounds(new Rectangle(150, 205, 645, 365));
        jPanelLayout.add(jLabel1, null);
        jPanelLayout.add(jSeparator5, null);
        jPanelLayout.add(close, null);
        jPanelLayout.add(jPanel2, null);
        jPanelLayout.add(jLabel2, null);
        jPanelLayout.add(jcboMonth, null);
        jPanelLayout.add(jcboYear, null);
        jPanelLayout.add(stop, null);
        jPanelLayout.add(start, null);
        jPanelLayout.add(scrollPaneMessage, BorderLayout.CENTER);
        jPanelLayout.add(scrollPaneHospitalCode, null);
        jPanelLayout.add(scrollPane, null);
        jPanelLayout.add(jPanel1, null);
        jPanelLayout.add(jPanel3, null);
        jPanelLayout.add(jTextArea1, null);
        jPanelLayout.add(jSeparator4, null);
        jPanelLayout.add(jSeparator1, null);
        tblMessage.setAutoscrolls(true);
        tblMessage.setAutoResizeMode(0);


        //        start.setText("Start");
        start.setBounds(new Rectangle(560, 115, 55, 30));
        start.setActionCommand("Start");
        start.setToolTipText("Start");
        //        stop.setText("Stop");
        stop.setBounds(new Rectangle(625, 115, 55, 30));
        stop.setActionCommand("Stop");
        stop.setToolTipText("Stop");
        //        close.setText("Close");
        close.setBounds(new Rectangle(695, 115, 55, 30));
        close.setActionCommand("Close");
        close.setToolTipText("Close");
        jSeparator4.setBounds(new Rectangle(25, 110, 765, 90));

        jcboYear.setBounds(new Rectangle(425, 75, 85, 25));
        jcboYear.setSelectedItem(JDate.getYear());
        jcboYear.setToolTipText("YYYY");
        jcboMonth.setBounds(new Rectangle(375, 75, 50, 25));
        jcboMonth.setSelectedItem(JDate.getMonth());
        jcboMonth.setToolTipText("MM");
        jLabel2.setText("Month :");
        jLabel2.setBounds(new Rectangle(320, 75, 65, 25));
        jLabel2.setFont(new Font("Dialog", 1, 12));
        jLabel2.setForeground(new Color(66, 66, 66));

        jLabel1.setText("0/0");
        jLabel1.setForeground(new Color(82, 82, 82));
        jLabel1.setFont(new Font("Dialog", 1, 12));
        jLabel1.setBounds(new Rectangle(715, 185, 70, 20));
        jLabel1.setHorizontalTextPosition(SwingConstants.RIGHT);
        jLabel1.setHorizontalAlignment(SwingConstants.RIGHT);
        jPanel1.setBounds(new Rectangle(25, 65, 765, 45));
        jPanel1.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
        jPanel1.setBackground(new Color(214, 214, 214));
        jPanel1.setForeground(Color.white);
        jPanel2.setBounds(new Rectangle(25, 25, 765, 40));
        jPanel2.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jPanel2.setBackground(new Color(99, 99, 99));
        jPanel2.setForeground(Color.white);
        jPanel3.setBounds(new Rectangle(25, 110, 765, 40));
        jPanel3.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
        jPanel3.setBackground(new Color(99, 99, 99));
        jPanel3.setForeground(Color.white);
        jTextArea1.setBounds(new Rectangle(20, 20, 775, 135));
        jTextArea1.setBackground(new Color(231, 231, 231));
        jSeparator1.setBounds(new Rectangle(25, 65, 765, 115));
        jSeparator5.setBounds(new Rectangle(20, 180, 775, 30));
        getLstHospitalCode().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        jPanelLayout.add(scrollPane, null);
        getContentPane().add(jPanelLayout, BorderLayout.CENTER);

        if (connect()) { 
            Batch b = new Batch(Variables.getHospitalCode(), this.conn);
            jcboMonth.addItem(Batch.getMm());
            jcboYear.addItem(Batch.getYyyy());
        } else { 
            DialogBox.ShowError("ไม่สามารถติดต่อกับฐานข้อมูลได้");
        } 
        
    }
    
    @Override
    public DefaultListModel elementAdd(String hospitalCode) {
        DefaultListModel r = new DefaultListModel();

            String sql = "SELECT DISTINCT D.CODE AS CODE, D.NAME_THAI AS NAME_THAI" + 
                            " FROM TRN_DAILY T INNER JOIN DOCTOR D ON T.DOCTOR_CODE=D.CODE AND T.HOSPITAL_CODE=D.HOSPITAL_CODE" +
                            " WHERE ";
            sql = sql + " D.ACTIVE = '1' " +
                   " AND D.HOSPITAL_CODE = '" + hospitalCode + "'" +
                    " and (T.BATCH_NO is null or T.BATCH_NO = '')" + 
                    " and T.EXCLUDE_TREATMENT != 'Y' " +       // very important
                    " and T.YYYY='" + Batch.getYyyy() + "' and T.MM='" + Batch.getMm() + "'" +
                    " and T.DOCTOR_CODE is not null AND T.DOCTOR_CODE != '' " +
                    " and T.ACTIVE = '1' " +
                    " and T.COMPUTE_DAILY_DATE is not null AND T.COMPUTE_DAILY_DATE != '' " +
                    " and (T.PAY_BY_CASH='Y' OR T.PAY_BY_AR='Y' OR T.PAY_BY_DOCTOR='Y' OR T.PAY_BY_PAYOR='Y' OR T.PAY_BY_CASH_AR='Y')" +
                    " and T.IS_PAID = 'Y' ";
            sql = sql + " ORDER BY D.CODE";
        ResultSet rs = conn.executeQuery(sql);
        try {
            r.clear();
            while (rs.next()) {
                r.addElement(rs.getString("CODE"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
               //Clean up resources, close the connection.
               if(rs != null) {
                  try {
                     rs.close();
                     rs = null;
                    }
                  catch (Exception ignored) { ignored.printStackTrace();   }
            }
        }
        return r;
    }

    @Override
    protected void start_actionPerformed(ActionEvent e) {
        // running ใช้สำหรับ ตรวจสอบว่ามีการกดปุ่ม stop หรือไม่
        if (this.conn.IsClosed()) { this.connect(); }
//        if (connect()) {
            addHospitalCodeToList();
            this.setProcess( new ProcessTransMonthly(this.conn) );
            this.getProcess().setCalculatorFrm(this);
            this.getProcess().running = true;
            this.getProcess().working = true;
            this.setRun();
            this.getProcess().start();
//        } else { 
//            DialogBox.ShowError("ไม่สามารถติดต่อกับฐานข้อมูลได้");
//        } 
    }
    
    @Override
    protected void stop_actionPerformed(ActionEvent e) {
        this.stopProcess();
    }
    
    @Override
    @SuppressWarnings("static-access")
    protected void close_actionPerformed(ActionEvent e) {
        try {
//        this.setVisible(false);
            URL url = new URL("http://localhost:8080/doctorfee");
            HttpURLConnection connection;
            try {
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                connection.setAllowUserInteraction(false);
                connection.setFollowRedirects(false);
                connection.connect();
            } catch (IOException ex) {
                Logger.getLogger(SummaryMonthlyFrm.class.getName()).log(Level.SEVERE, null, ex);
            }

            
            
        } catch (MalformedURLException ex) {
            Logger.getLogger(SummaryMonthlyFrm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }    
/*
    private void this_componentResized(ComponentEvent e) {
        scrollPaneMessage.setSize(jPanelLayout.getWidth()-110, jPanelLayout.getHeight()-60);
        this.scrollPane.setSize(this.scrollPane.getWidth(), jPanelLayout.getHeight()-185);
        jToolBarDFCalculator.setSize(jPanelLayout.getWidth(), jToolBarDFCalculator.getHeight());
    } */
    public String getMM() {
        return this.jcboMonth.getSelectedItem().toString();
    }
    public String getYYYY() {
        return this.jcboYear.getSelectedItem().toString();
    }
    
    @Override
    public DefaultListModel elementAddToHospitalCodeList() {
        DefaultListModel r = new DefaultListModel();
        r.addElement(hospitalCode);
        return r;
    }
    
    @Override
    public void stopProcess() {
        if (this.getProcess() != null) {
            this.getProcess().running = false;
            this.getProcess().working = false;
            this.setStop();     
        }
    }
    
    @Override
    public void setRun() {
        this.start.setEnabled(false);
        this.stop.setEnabled(true);
    }
    @Override
    public void setStop() {
        this.start.setEnabled(true);
        this.stop.setEnabled(false);        
    }
    @Override
    public void setCount(String mess) {
        this.jLabel1.setText(mess);
    }
    

}
